package com.yztc.yidoutang.utils;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.yztc.yidoutang.bean.SearchHistoryBean;
import com.yztc.yidoutang.share.SharedURL;

import java.sql.SQLException;

/**
 * Created by My on 2016/10/19.
 */

public class MySqliteOpenHelper extends OrmLiteSqliteOpenHelper{

    private static MySqliteOpenHelper helper;
    private Dao<SearchHistoryBean,Integer> searchHistoryDao;

    private MySqliteOpenHelper(Context context) {
        super(context, SharedURL.DB_NAME, null, SharedURL.DB_VERSION);
    }
    public static MySqliteOpenHelper getInstance(Context context){
        if (helper==null){
            helper=new MySqliteOpenHelper(context);
        }
        return helper;
    }

    public Dao<SearchHistoryBean,Integer> getSearchHistoryDao(){
        if (searchHistoryDao==null){
            try {
                searchHistoryDao=getDao(SearchHistoryBean.class);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return searchHistoryDao;
    }
    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource,SearchHistoryBean.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        if (oldVersion<newVersion){
            try {
                TableUtils.dropTable(connectionSource,SearchHistoryBean.class,true);
                TableUtils.createTable(connectionSource,SearchHistoryBean.class);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
